<template>
  <div
    :class="['wy-panel', 'frame', isExpand ? 'is--max' : '']"
    v-if="config.name"
  >
    <div class="mask-container" v-if="isMask"></div>
    <div class="none-container" v-if="nonePermission">
      {{ $srv.getI18nByPath('others.noPermissions') }}···
    </div>
    <Split
      :style="extraCollaStyle"
      class="wy-panel-split"
      v-model="extraSpace.split"
      :mode="extraSpace.mode"
      min="0"
      max="0"
    >
      <div class="extra-container" :slot="extraSpace.extraPosition">
        <div class="extra-content">
          <div class="extra-bancodeScan" v-if="extraSpaceRole.bancodeScan">
            <cBarcodeScan
              :compBoxInfo="GT_compBoxInfo"
              :parentCommand="GT_command"
            />
          </div>
        </div>
      </div>
      <div class="main-container" :slot="extraSpace.mainPosition">
        <Split v-model="searchControl.split" min="0" max="0">
          <div class="panel-content" slot="left">
            <!-- <div
                class="tags"
                :style="{ display: tagsControl.audit ? 'flex' : 'none' }"
              >
                <div
                  class="audit-checked"
                  :style="{ display: tagsControl.audit ? 'flex' : 'none' }"
                >
                  <Icon custom="wy-icon wy-yishenhe"></Icon>
                </div>
              </div> -->
            <!-- 单据标签 -->
            <div
              class="tags"
              :style="{ display: tagsControl.normal ? 'none' : 'flex' }"
            >
              <div
                class="audit-checked"
                :style="{ display: tagsControl.normal ? 'none' : 'flex' }"
              >
                <Icon
                  v-if="tagsControl.audit"
                  color="indianred"
                  custom="wy-icon wy-yishenhe"
                ></Icon>
                <Icon
                  v-if="tagsControl.approval"
                  color="#DE6A12"
                  custom="wy-icon wy-shenhezhong"
                ></Icon>
                <Icon
                  v-else-if="tagsControl.accountPosted"
                  color="#03fd6d"
                  custom="wy-icon wy-yiguozhang"
                ></Icon>
                <Icon
                  v-else-if="tagsControl.caseclosed"
                  color="indianred"
                  custom="wy-icon wy-close-a-ase"
                ></Icon>
                <Icon
                  v-else-if="tagsControl.freeze"
                  color="#707070"
                  custom="wy-icon wy-yidongjie"
                ></Icon>
                <Icon
                  v-else-if="tagsControl.void"
                  color="indianred"
                  custom="wy-icon wy-yizuofei"
                ></Icon>
              </div>
            </div>
            <!-- 顶部toolbar按钮 -->
            <div class="panel-toolbar">
              <o-toolbar
                @commit-event="commitEvent"
                :config="toolbar"
                :current="pageNo"
                :total="total"
                :compBoxInfo="GT_compBoxInfo"
              ></o-toolbar>
            </div>
            <!-- 上form -->
            <div
              :class="[
                'y-scroll',
                'panel-form',
                'panel-tabs',
                { 'panel-single': isPanelSingle }
              ]"
            >
              <Tabs
                :name="randomTabName"
                :animated="false"
                type="card"
                v-model="activeTab"
                v-if="
                  $srv.getx(config, 'panelLayout.formLayout', 'tabs') === 'tabs'
                "
              >
                <template v-for="(form, idx) of forms">
                  <TabPane
                    v-if="!form.content.formStyle.isBottom"
                    :label="$srv.getI18nBySrv(form.label)"
                    :tab="randomTabName"
                    :key="idx"
                    :name="idx + ''"
                  >
                    <!-- :ref="'panelForm_' + idx" -->
                    <o-base-form
                      :config="form.content"
                      :parentFunName="funName.formName"
                      :parentName="name.formName"
                      :parentCommand="GT_command"
                      :parentID="idx"
                      :mode="2"
                      @compBoxInfo="regInstance($event, 'form', `${idx}`)"
                      @on-change="receiveBaseFormDataPkg"
                    ></o-base-form>
                  </TabPane>
                </template>
              </Tabs>
              <Collapse
                v-model="activePanel"
                v-if="
                  $srv.getx(config, 'panelLayout.formLayout', 'tabs') ===
                    'collapse'
                "
              >
                <template v-for="(form, idx) of forms">
                  <Panel
                    v-if="!form.content.formStyle.isBottom"
                    :name="form.label"
                    :key="idx"
                  >
                    {{ $srv.getI18nBySrv(form.label) }}
                    <template #content>
                      <o-base-form
                        :config="form.content"
                        :parentFunName="funName.formName"
                        :parentName="name.formName"
                        :parentID="idx"
                        :mode="2"
                        @compBoxInfo="regInstance($event, 'form', `${idx}`)"
                        @on-change="receiveBaseFormDataPkg"
                      ></o-base-form
                    ></template>
                  </Panel>
                </template>
              </Collapse>
            </div>
            <!-- 中表格 -->
            <div class="panel-table panel-tabs" v-if="useTable">
              <Tabs
                :name="randomTabName"
                v-model="currentTableIndex"
                :animated="false"
                type="card"
                style="height: 100%"
              >
                <TabPane
                  v-for="(table, idx) of tables"
                  :label="$srv.getI18nBySrv(table.label)"
                  :tab="randomTabName"
                  :key="idx"
                  :name="'table_' + idx"
                >
                  <!-- :ref="'panelTable_' + idx" -->
                  <o-base-grid
                    :config="table.content"
                    :parentName="name.tableNames[idx]"
                    :isUseEditLock="false"
                    :parentID="idx"
                    :isCoordination="false"
                    @compBoxInfo="regInstance($event, 'table', `${idx}`)"
                    @on-change="receiveBaseGridDataPkg"
                  ></o-base-grid>
                </TabPane>
              </Tabs>
            </div>
            <!-- 下·form -->
            <div
              :class="[
                'panel-form',
                'panel-form-bottom',
                $srv.utils.filter(forms, el => el.content.formStyle.isBottom)
                  .length === 1
                  ? 'panel-single'
                  : ''
              ]"
              v-if="
                $srv.utils.filter(forms, el => el.content.formStyle.isBottom)
                  .length > 0
              "
            >
              <Tabs :name="randomTabName" :animated="false" type="card">
                <template v-for="(form, idx) of forms">
                  <!-- 底部form -->
                  <TabPane
                    v-if="form.content.formStyle.isBottom"
                    :label="$srv.getI18nBySrv(form.label)"
                    :tab="randomTabName"
                    :key="idx"
                  >
                    <!-- :ref="'panelForm_' + idx" -->
                    <o-base-form
                      :config="form.content"
                      :parentFunName="funName.formName"
                      :parentName="name.formName"
                      :parentID="idx"
                      @compBoxInfo="regInstance($event, 'form', `${idx}`)"
                      @on-change="receiveBaseFormDataPkg"
                      :mode="2"
                    ></o-base-form>
                  </TabPane>
                </template>
              </Tabs>
            </div>
          </div>
          <!-- 右侧隐藏查找操作UI -->
          <div class="panel-search" slot="right">
            <div class="panel-search-header">
              <div class="panel-search-left">
                <Button
                  type="text"
                  :title="$srv.getI18nByPath('vxe.toolbar.expand')"
                  @click="commitEvent('adjustSearchWidth')"
                  ><Icon custom="wy-icon wy-xiangzuo"/></Button
                ><Button
                  type="text"
                  :title="$srv.getI18nByPath('vxe.toolbar.close')"
                  @click="commitEvent('closeSearch')"
                  ><Icon custom="wy-icon wy-guanbi"/></Button
                ><span>{{
                  $srv.getI18nByPath('vxe.search.searchConfirm')
                }}</span>
              </div>
              <div class="panel-search-right">
                <Button type="text" @click="commitEvent('openSearchBox')"
                  ><Icon custom="wy-icon wy-sousuo13" /><b class="toolText">{{
                    $srv.getI18nByPath('vxe.search.advSearchCheck')
                  }}</b></Button
                >
              </div>
            </div>
            <div class="panel-search-simple-form">
              <div>
                <!-- ref="simpSearchForm" -->
                <o-base-form
                  @submit="doSimpleSearch"
                  :mode="1"
                  @compBoxInfo="regInstance($event, 'form', 'simpSearchForm')"
                ></o-base-form>
              </div>
            </div>
            <div class="panel-search-result">
              <!-- ref="searchGrid" -->
              <o-base-grid
                :isUseEditLock="false"
                :isCoordination="false"
                @on-row-change="handleSearchResultChange"
                :mode="1"
                @compBoxInfo="regInstance($event, 'table', 'searchGrid')"
              ></o-base-grid>
            </div>
          </div>
        </Split>
      </div>
    </Split>
    <o-modal
      v-model="searchControl.isSearchBoxOpen"
      :mask="false"
      :size="[400, 700]"
      :title="$srv.getI18nByPath('vxe.search.advSearchCheck')"
      :keep-alive="true"
      @on-ok="doFullSearch"
      @on-cancel="() => {}"
    >
      <template v-slot:content>
        <div class="custom-search">
          <div class="search-conditions" v-if="searchForms !== null">
            <div
              class="condition-form"
              v-for="(form, key) in searchForms"
              :key="key"
            >
              <span>{{ $srv.getI18nBySrv(key) }}</span>
              <div class="cover">
                <div class="condition-forms">
                  <!-- :ref="'searchForm_' + key" -->
                  <o-base-form
                    @compBoxInfo="regInstance($event, 'searchForm', `${key}`)"
                    :mode="1"
                  ></o-base-form>
                </div>
                <div class="condition-select">
                  <template v-for="(item, idx) of form">
                    <Checkbox
                      v-if="!item.folding"
                      :key="idx"
                      :value="selectedSearchFields[key][item.field]"
                      @on-change="
                        selectSimpleSearchField(key, item.field, $event)
                      "
                    ></Checkbox>
                  </template>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template v-slot:footer>
        <Button class="custom-search-reset" @click="resetSearchForm">{{
          $srv.getI18nByPath('vxe.menu.reset')
        }}</Button>
      </template>
    </o-modal>

    <o-modal
      v-model="isOpenPrint"
      :title="$srv.getI18nByPath('vxe.print.selPrintTemp')"
      :size="[300, 400]"
      :mask="true"
      :tap-close="true"
      @on-ok="doPrint"
    >
      <o-print-panel
        slot="content"
        :funID="funID"
        @on-change="val => (selectedPrintTemp = val)"
      ></o-print-panel>
    </o-modal>
  </div>
</template>
<script lang="ts">
import {
  EDIT_STATE,
  Getter,
  I_command,
  N_oBaseGrid,
  N_oSetupPanel,
  T_command,
  T_srv,
  Tsrv,
  ifs,
  oModal,
  oToolbar,
  ts,
  vue,
  vxeConfig
} from './config';

@T_srv.comp({
  components: {
    oToolbar,
    oModal
  }
})
export default class oBasePanel extends vue {
  [x: string]: any;

  /**
   * props
   */
  @T_srv.prop({
    required: true
  })
  config!: any;

  @T_srv.prop({
    required: false,
    type: Boolean,
    default: true
  })
  useTable!: boolean;

  @Getter('Language') language;

  @T_srv.inject({ default: () => {} }) addTabFunc;

  /**
   * 配置属性
   */
  private toolbar = null;

  /**
   * 控制属性
   */
  private needSave = false;

  // 随机获取tab的id
  private randomTabName: string = Tsrv.utils.uniqueId('tab_');

  // 是否在加载
  private loading: boolean = false;

  // 是否扩展
  public isExpand: boolean = false;

  // 是否打印开启
  public isOpenPrint: boolean = false;

  public isMask: boolean = false;

  // 打印模版选择
  public selectedPrintTemp: string = '';

  private listenType: string = '';

  public isPanelSingle: boolean = false;

  private searchControl = {
    split: 1,
    isSearchOpen: false,
    isSearchBoxOpen: false,
    isSearchFullOpen: false
  };

  private pageNo: number = 1;

  // 页数
  private total: number = 0;

  // 总页
  private tagsControl = {
    normal: false,
    audit: false,
    approval: false,
    accountPosted: false,
    caseclosed: false,
    freeze: false,
    void: false
  };

  /**
   * 功能属性
   */
  // 所有表的名称
  private name: {
    formName: string | null;
    tableNames: string[];
  } = {
    formName: null,
    tableNames: []
  };

  private funName: {
    formName: string | null;
    tableNames: string[];
  } = {
    formName: null,
    tableNames: []
  };

  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  // 更换总线事件名
  // 1.0通过内部默认事件在组件间通讯
  // 当标准baseGrid为定制程序里的组件时会存在相互干扰
  @T_srv.prop({
    required: false,
    type: Array,
    default: () => []
  })
  regCustEventName: Array<N_oBaseGrid.I_regCustEventName>;

  /* 组件名 */
  private G_compName: string = 'oBasePanel';

  /* 组件箱信息对象 */
  private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  private G_compID: string;

  private _config: any;

  private formID = null;

  // 表头的ID
  private forms = null;

  // 表头组的数量
  private formData = {}; // 表头的数据

  private currentTableIndex: string = 'table_0';

  private tables = null;

  // 所有表体的属性
  private tablesLength = 0; // 表体个数

  private searchForms = null;

  // 用于搜索的全部列属性
  private selectedSearchFields = {};

  // 快捷搜索的表列
  private simpleSearchForm = [];

  // 用快捷搜索的列属性
  private actionsCfg: any = {};

  private hasRequestAudit: boolean = false;

  private GT_command: I_command = undefined;

  private funID: string = '-1';

  // 已调入编辑锁资料
  private isLoadEditLock: boolean = false;

  public activeTab = null;

  // public activePanel = [];
  private currDefaultBusEventName: string = '';

  private defListenersEventNames: Array<string> = [];

  private bpaStaging: any = null;

  private customPermission: any = null;

  private customBtnStatus: Array<object> = [];

  private nonePermission: boolean = false;

  private extraSpace = {
    split: 0,
    mode: 'vertical',
    extraPosition: 'top',
    mainPosition: 'bottom'
  };

  // 分割面板样式
  private extraCollaStyle: any = { '--splitTrigger': 'none' };

  private extraSpaceRole: any = {
    bancodeScan: false
  };

  private initFilter: ifs.I_fv[] = [];

  get activePanel(): Array<string> {
    return this.forms.map(item => item.label);
  }

  // eslint-disable-next-line no-empty-function
  set activePanel(value: Array<string>) {}

  created() {
    this._config = Tsrv.utils.clone(this.config, true);
    this.GT_compBoxInfo = Tsrv.getCompInfo(this.compBoxInfo);
    this.G_compID = this.GT_compBoxInfo.compID;
    this.GT_compBox = this.GT_compBoxInfo.TcompBox;
    this.GT_command = new T_command(this, this.GT_compBoxInfo);
    this.GT_compBox.addCompMergeName(
      this.G_compID,
      'oBasePanelCMD',
      this.GT_command
    );
    this.funID = Tsrv.getMinFunID(this.config.mainFun);
    this.GT_command.editorState = EDIT_STATE.BROWSE;
    this.GT_command.init(this.useTable);
    this.setActions(this.config.action);
    this.GT_command.newTcompCoordination(this.config);

    // 功能“浏览”权限
    const defaultPermission = Tsrv.utils.find(
      this.config.permission,
      item => item.area === 'default'
    );
    this.nonePermission = !defaultPermission?.data?.browse;
  }

  destroyed() {
    /* 注册组件销毁 */
    this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);
    /* 如果父组件传入的compBoxInfo则删除本文件产生的引用,反之是本组件产生的ID统一删除 */
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, [
        `'${this.G_compName}'`
      ]);
    }
    /* 最终应用组件销毁 */
    Tsrv.compBox.removeCompMergeName(
      Tsrv.compBox.getDefGUID(),
      this.name.formName
    );
    /* 如果是动态组件可能会关闭全局compBox */
    // this.GT_compBox = null
  }

  mounted() {
    this.$emit('compBoxInfo', this.GT_compBoxInfo);
    this.GT_compBox.addCompMergeName(this.G_compID, this.G_compName, this);
    /* 最终应用组件向外抛出引用实例,以供应用间调用 */
    // 可不用注册，home组件中有注册（在openfun中）
    Tsrv.compBox.addCompMergeName(
      Tsrv.compBox.getDefGUID(), // 全局compBox
      this.name.formName,
      this
    );

    this.listenType = this.config['listenType'] || 'default';
    this.getDefListener();
    this.defListenersEventNames.forEach(eN => {
      const newEventName: string = this.GT_command.getRegEventName(
        'receive',
        eN
      );
      // eN 如果没有custDefListener,eN默认为功能名
      this.currDefaultBusEventName = newEventName ?? eN;
      if (this.listenType === 'default') {
        this.$bus.$on(newEventName ?? eN, (msg: any) => {
          if (msg.listenType === this.listenType || msg.type === 'coordination')
            this.handleListener(msg);
        });
      } else {
        this.$mbus.$on(newEventName ?? eN, (msg: any) => {
          if (msg.listenType === this.listenType) this.handleListener(msg);
        });
      }
    });

    // this.activePanel = this.forms.map(item => item.label);

    // 加载表头数据，然后加载表体
    this.$nextTick(() => {
      this.$emit('mounted', this);
      this.loadFormData(1, this.initFilter).then(res => {
        if (res !== undefined) {
          this.loadTableData();
          this.$emit('loadFormData', res);
        }
      });
    });
    if (this.actionsCfg?.openFun) {
      this.handleActions(this.actionsCfg.openFun, 'openFun');
    }
  }

  beforeDestroy() {
    if (this.actionsCfg?.closeFun) {
      this.handleActions(this.actionsCfg.closeFun, 'closeFun');
    }
    this.$bus.$off(this.funName.formName);
    if (this.listenType === 'default') {
      this.defListenersEventNames.forEach(eN => {
        this.$bus.$off(
          this.GT_command.getRegEventName('receive', 'selBillMagicBox') ?? eN
        );
      });
    } else {
      this.defListenersEventNames.forEach(eN => {
        this.$mbus.$off(
          this.GT_command.getRegEventName('receive', 'selBillMagicBox') ?? eN
        );
      });
    }
  }

  private handleListener(msg: any) {
    switch (msg.type) {
      case 'requestFilter':
        this.handleRequstFilter(msg.val);
        break;
      case 'search':
        this.handleFilter(msg);
        break;

      // 组件协调事件
      case 'coordination':
        // cbaseForm
        if (!this.useTable) {
          this.GT_command.receEventCoordination(msg);
        }
        break;

      default:
        break;
    }
  }

  private getDefListener() {
    const custDefListener = this.config?.messageConfig?.custDefListener;
    if (!Tsrv.utils.noValue(custDefListener)) {
      let isNull = true;
      Object.keys(custDefListener).forEach(key => {
        if (!Tsrv.utils.noValue(custDefListener[key])) {
          isNull = false;
          if (Array.isArray(custDefListener[key])) {
            this.defListenersEventNames.push(...custDefListener[key]);
          } else if (typeof custDefListener[key] === 'string') {
            this.defListenersEventNames.push(custDefListener[key]);
          } else {
            throw new Error(`无法识别的事件监听[${custDefListener[key]}]`);
          }
        }
      });
      if (isNull) {
        this.defListenersEventNames.push(this.funName.formName);
      }
    } else {
      this.defListenersEventNames.push(this.funName.formName);
    }
  }

  public requestFilter(cfg: any) {
    this.handleRequstFilter(cfg);
  }

  private handleRequstFilter(cfg: any) {
    if (cfg.length > 0) {
      if (cfg[0].field === 'id') {
        this.getRecordIndexById(cfg[0].value).then((index: number) => {
          if (index) {
            this.pageNo = index;
            this.loadFormData(index).then(res => {
              if (res !== undefined) {
                this.loadTableData();
                this.$emit('loadFormData', res);
              }
            });
          } else {
            this.$msg(Tsrv.getI18nByPath('warm.noBill'));
          }
        });
      }
    }
  }

  private handleFilter(msg: any) {
    const cfg = msg.content;
    // this.getRecordIndexById(cfg.val[0]).then((index: number) => {
    //   if (index) {
    //     this.pageNo = index;
    //     this.loadFormData(index).then(res => {
    //       if (res !== undefined) {
    //         this.loadTableData();
    //         this.$emit('loadFormData', res);
    //       }
    //     });
    //   } else {
    //     this.$msg(Tsrv.getI18nByPath('warm.noBill'));
    //   }
    // });
    this.loadFormData(1, [
      { field: cfg.ukey, value: `${cfg.val[0]}` }
    ] as ifs.I_fv[]).then(res => {
      if (!Tsrv.utils.noValue(res)) {
        this.loadTableData();
        this.$emit('loadFormData', res);
      }
    });
  }

  // form实例注册到指挥部
  private regInstance(
    compBoxInfo: ifs.I_compBoxInfo,
    typ: string,
    key: string
  ) {
    this.GT_command.regInstance(compBoxInfo, typ, key);
  }

  private setActions(config: any) {
    if (Tsrv.utils.isPlainObject(config)) {
      this.actionsCfg = config;
    }
  }

  /**
   * 搜索
   */
  // 监听搜索结果表事件
  private handleSearchResultChange(data: any) {
    if (data.data.to) {
      data = data.data.to.row;
      if (data.id) {
        if (data.id !== this.formID) {
          // this.getRecordIndexById(data.id).then((index: number) => {
          //   if (index) {
          //     this.pageNo = index;
          //     this.loadFormData(index).then(res => {
          //       if (res !== undefined) this.loadTableData();
          //     });
          //   }
          // });

          this.loadFormData(1, [
            { field: 'id', value: `${data.id}` }
          ] as ifs.I_fv[]).then(res => {
            if (res !== undefined) {
              this.$emit('loadFormData', res);
              this.loadTableData();
            }
          });
        }
      }
    }
  }

  // 选择了简易搜索的条件
  private selectSimpleSearchField(table: string, field: string, val: boolean) {
    this.selectedSearchFields[table][field] = val;
    this.simpleSearchForm = [];
    const d = this.selectedSearchFields;
    for (const t in d) {
      for (const f in d[table]) {
        if (d[t][f] === true) {
          this.simpleSearchForm = this.simpleSearchForm.concat(
            this.searchForms[t].filter(el => el.field === f)
          );
        }
      }
    }
    this.simpleSearchForm.push({
      align: 'center',
      span: 2,
      itemRender: {
        name: '$button',
        props: {
          type: 'submit',
          // content: "搜索",
          content: Tsrv.getI18nByPath('oReportEditor.search'),
          status: 'primary'
        }
      }
    });

    this.simpleSearchForm.forEach(el => {
      if (el.itemRender) {
        el.itemRender.events = null;
      }
    });
    this.GT_command.getFormInstance('simpSearchForm').setColumns(
      this.simpleSearchForm
    );
    this.GT_command.getFormInstance('simpSearchForm').setColumnNumber(
      null,
      true
    );
  }

  // 重置高级搜索的条件
  public resetSearchForm() {
    Object.keys(this.searchForms).forEach(key => {
      this.GT_command.getSearchFormInstance(key).clearFormData();
    });
    this.doFullSearch();
  }

  // 执行简易搜索
  public doSimpleSearch() {
    let searchConditions = [];
    let searchFields = [];
    searchConditions = this.GT_command.getFormInstance(
      'simpSearchForm'
    ).getFilterData({
      hasM2o: true
    });
    Object.keys(this.searchForms).forEach(key => {
      if (key === this.name.formName) {
        searchFields = searchFields.concat(
          Object.keys(this.searchForms[key])
            .filter(el => this.searchForms[key][el].field.indexOf('|') < 0)
            .map(el => {
              return {
                tableName: key,
                field: this.searchForms[key][el].field
              };
            })
        );
      }
    });
    const subTableKeyFields = [];
    this.name.tableNames.forEach((name, index) => {
      subTableKeyFields.push({
        tableName: name,
        keyField: this.GT_command.getTableInstance(index).keyField
      });
    });
    if (searchConditions.length === 0) {
      searchConditions.push({
        field: 'id',
        value: `>0`,
        tableName: this.name.formName
      });
    }
    const searchParams = {
      returnFields: searchFields,
      conditions: searchConditions,
      lang: this.language,
      tables: {
        mainTableName: this.name.formName,
        mainTableKeyField: 'id',
        subTableKeyFields
      }
    };
    const searchGrid = this.GT_command.getTableInstance('searchGrid');
    searchGrid.tablePage.currentPage = 1;
    searchGrid.setAdvqParams(searchParams);
    searchGrid.GT_editor.loadTableDataAdvq().then((res: any) => {
      if (res) {
        for (let i = 0; i < res.length; i++) {
          if (res[i].id === this.formID) {
            searchGrid.grid.setCurrentRow(res[i]);
            break;
          }
        }
        this.$msg(`50004,FE,0,${res.length}`);
      }
    });
  }

  // 执行高级搜索
  private doFullSearch() {
    let searchConditions = [];
    let searchFields = [];
    Object.keys(this.searchForms).forEach(key => {
      const arr = this.GT_command.getSearchFormInstance(key).getFilterData({
        hasM2o: true
      });
      searchConditions = searchConditions.concat(
        arr.map(el => {
          el['tableName'] = key;
          return el;
        })
      );
      if (key === this.name.formName) {
        searchFields = searchFields.concat(
          Object.keys(this.searchForms[key])
            .filter(el => this.searchForms[key][el].field.indexOf('|') < 0)
            .map(el => {
              return {
                tableName: key,
                field: this.searchForms[key][el].field
              };
            })
        );
      }
    });
    const subTableKeyFields = [];
    this.name.tableNames.forEach((name, index) => {
      subTableKeyFields.push({
        tableName: name,
        keyField: this.GT_command.getTableInstance(index).keyField
      });
    });
    if (searchConditions.length === 0 && this.formID) {
      // formID  2.0的formID已换成雪花ID，设置范围已无意义
      // let startID;
      // const endID = this.formID + 20;
      // if (this.formID >= 20) {
      //   startID = this.formID - 20;
      // }
      // searchConditions.push({
      //   field: 'id',
      //   value: `${startID}-${endID}`,
      //   tableName: this.name.formName
      // });
      searchConditions.push({
        field: 'id',
        value: `>0`,
        tableName: this.name.formName
      });
    }
    const searchParams = {
      returnFields: searchFields,
      conditions: searchConditions,
      lang: this.language,
      tables: {
        mainTableName: this.name.formName,
        mainTableKeyField: 'id',
        subTableKeyFields
      }
    };
    const searchGrid = this.GT_command.getTableInstance('searchGrid');
    searchGrid.tablePage.currentPage = 1;
    searchGrid.setAdvqParams(searchParams);
    searchGrid.GT_editor.loadTableDataAdvq().then((res: any) => {
      this.searchControl.isSearchBoxOpen = false;
      if (res) {
        this.$msg(`50004,FE,0,${res.length}`);
      }
    });
  }

  // 关闭搜索
  private closeSearch() {
    this.searchControl.split = 1;
    this.searchControl.isSearchBoxOpen = false;
    this.searchControl.isSearchOpen = false;
  }

  private openSearch() {
    // 控制打开
    this.searchControl.split = 0.6;
    this.searchControl.isSearchBoxOpen = false;
    this.searchControl.isSearchOpen = true;

    if (this.searchForms === null) {
      const items = {};
      items[this.name.formName] = [];
      this.selectedSearchFields[this.name.formName] = {};

      // 表头的检索
      for (let i = 0; i < this.GT_command.formsNum; i++) {
        const formItems = Tsrv.utils
          .clone(this.GT_command.getFormInstance(i).form.items, true)
          .filter(el => {
            // return el.field !== '_file_' && el.field !== 'id';
            return el.field !== '_file_info_id_' && el.field !== 'id';
          })
          .map(el => {
            el['params']['table'] = this.name.formName;
            el.itemRender = vxeConfig.getSearchRender(el.itemRender);
            return el;
          });
        items[this.name.formName] = items[this.name.formName].concat(formItems);
      }

      // 表体的检索
      this.name.tableNames.forEach((name, index) => {
        items[name] = [];
        const grid = Tsrv.utils.clone(
          this.GT_command.getTableInstance(index).grid.columns,
          true
        );
        grid.forEach(el => {
          if (el.editRender && el.field !== 'id') {
            el.itemRender = vxeConfig.getSearchRender(el.editRender);
            delete el.editRender;
            el['params']['table'] = name;
            if (Tsrv.utils.noValue(el?.visible) || el.visible) {
              items[name].push(el);
            }
          }
        });
        this.selectedSearchFields[name] = {};
      });

      // 设置表头
      this.searchForms = items;
      const style = {
        border: false,
        showHeader: true,
        showFooter: true,
        showPager: true
      };
      const searchGrid = this.GT_command.getTableInstance('searchGrid');
      // 添加国际化字段
      searchGrid.setFunI18nFields(this._config.funI18nFields);
      // 设置表名、功能名
      searchGrid.GT_editor.setFunName(this.name.formName).setTableName(
        this.name.formName
      );
      const columns = [];
      for (let i = 0; i < this.GT_command.formsNum; i++) {
        const cols = this.forms[i]?.content?.formColumns;
        if (!Tsrv.noValue(cols) && Array.isArray(cols)) {
          columns.push(...cols);
        }
      }
      const searchGridColumns = searchGrid
        .transformColumns(columns)
        .filter(el => {
          return el?.type !== 'checkbox' && el?.type !== 'seq';
        });

      searchGrid.setStyle(style);
      searchGrid.setColumns(searchGridColumns);

      setTimeout(() => {
        for (const key in items) {
          items[key].forEach(item => {
            if (item.params.isDefaultFilter) {
              this.selectSimpleSearchField(key, item.field, true);
            } else {
              searchGrid.setColumnVisible(item.field, false);
            }
          });
        }

        searchGrid.setDataSource('advq');
        const newItems = Tsrv.utils.clone(items, true);
        Object.keys(newItems).forEach((key, idx) => {
          const form = this.GT_command.getSearchFormInstance(key);
          newItems[key].forEach(el => {
            if (el.itemRender) {
              el.itemRender.events = null;
            }
          });
          form.setColumns(newItems[key]);
          form.setColumnNumber(1, true);
        });

        this.GT_command.getFormInstance('simpSearchForm').setColumnNumber(
          null,
          true
        );
        this.doSimpleSearch();
      }, 0);
    } else {
      const searchGrid = this.GT_command.getTableInstance('searchGrid');
      if (!Tsrv.noValue(searchGrid)) {
        this.doSimpleSearch();
      }
    }
  }

  private openSearchBox() {
    this.searchControl.isSearchBoxOpen = true;
  }

  public commitEvent(event: string, params = null) {
    switch (event) {
      case 'insert_actived':
        this.insert();
        if (!this.useTable) {
          this.GT_command.sendEventCoordination('insert');
        }
        break;
      case 'save':
        this.save();

        break;
      case 'prevRecord':
        this.prev();
        break;
      case 'nextRecord':
        this.next();
        break;
      case 'firstRecord':
        this.start();
        break;
      case 'lastRecord':
        this.end();
        break;
      case 'jumpToPage':
        this.jumpTo(Tsrv.utils.toNumber(params.target.value));
        break;
      case 'reload':
        this.GT_command.handleBtnActions('refresh', this.reload);
        break;
      case 'search':
        if (this.searchControl.isSearchOpen) {
          this.closeSearch();
        } else {
          this.openSearch();
        }
        break;
      case 'customBtnAction':
        this.doCustomBtnAction(params.title, params.action);
        break;
      case 'openSearchBox':
        this.openSearchBox();
        break;
      case 'closeSearch':
        this.closeSearch();
        break;
      case 'adjustSearchWidth':
        this.searchControl.split = this.searchControl.isSearchFullOpen
          ? 0.6
          : 0;
        this.searchControl.isSearchFullOpen ===
          !this.searchControl.isSearchFullOpen;
        break;
      case 'doSimpleSearch':
        this.doSimpleSearch();
        break;
      case 'print':
        this.print();
        break;
      case 'expand':
        this.isExpand = !!params;
        break;
      case 'edit':
        this.switchEdit(params);
        break;
      case 'check':
        this.auditCheck('check', params);
        break;
      case 'remove':
        if (!this.useTable) {
          this.GT_command.sendEventCoordination('delete');
        }
        this.delete();
        break;
      case 'attach':
        this.handleAttachClicked();
        break;
      case 'queryLink':
        this.queryLinkClick(params);
        break;
      case 'selbill':
        this.selbillClick(params);
        break;
      case 'bancodeScan':
        this.bancodeScanClick();
        break;
      case 'requestAudit':
        this.requestAudit(params);
        break;
      case 'auditStatus':
        this.auditStatus();
        break;
      case 'accountPost':
        this.accountPost(params);
        break;
      case 'caseclose':
        this.caseclose(params);
        break;
      case 'freeze':
        this.freeze(params);
        break;
      case 'void':
        this.void();
        break;

      default:
        break;
    }
  }

  private requestAudit(value: boolean) {
    if (value) {
      // 送审操作
      if (!Tsrv.noValue(this.formID)) {
        const funInfo = {
          funID: this.funID,
          funName: this.funName.formName
        };
        vxeConfig.doRequestAudit(funInfo, [this.formID]).then(resp => {
          if (resp) {
            this.auditCheck('requestAudit', value);
          }
        });
      }
    } else {
      // 反审操作
      this.auditCheck('antiAudit', value);
    }
  }

  // private sendMsg() {
  //   Tsrv.utils
  //     .createModal('o-send-message', {
  //       modalTitle: Tsrv.getI18nByPath('prompt.urgentLevel'),
  //       modalSize: [600, 500]
  //     })
  //     .then(res => {});
  // }

  // 废弃（现已无用）
  // private requestSendAudit(params) {
  //   Tsrv.httpReqV1.sendForAudit(params).then(res => {
  //     if (res.data.success) {
  //       const data = res.data.data;
  //       data ? this.requestSendSelect(data, params) : this.$msg(res.data.msg);
  //     } else {
  //       this.$msg(res.data.msg);
  //     }
  //   });
  // }

  private requestSendSelect(data, params) {
    Tsrv.utils
      .createModal('o-audit-select', {
        modalTitle: Tsrv.getI18nByPath('prompt.sendAuditRole'),
        modalSize: [200, 300],
        data
      })
      .then(res => {
        if (res) {
          params.select = {
            roleType: res.roleType,
            objId: res.objId
          };
          this.requestSendAudit(params);
        }
      });
  }

  private auditStatus() {
    // Tsrv.utils
    //   .createModal('o-audit-map', {
    //     modalTitle: Tsrv.getI18nByPath('prompt.lookAuditRecords'),
    //     modalSize: [400, 600],
    //     rowId: this.formID
    //   })
    //   .then(res => {});
  }

  // config.action 的 map
  // private standardBtnActions: Map<string, Map<string, string>> = new Map<
  //   string,
  //   Map<string, string>
  // >();

  // // 获取 config.action 中的 标准按钮的配置
  // private getStandardBtnActions() {}

  // // 标准按钮执行 前后 操作
  // private standardBtnClick(action: string) {
  // }

  private selbillClick(index: number) {
    if (index !== null) {
      const item = this.config.selbill[index];
      if (
        !Tsrv.utils.isEmpty(item.many2one.toTable) &&
        !Tsrv.utils.isEmpty(item.action)
      ) {
        if (!this.needSave) {
          const config = {};
          if (item.many2one) {
            const filterData = this.GT_command.getFormInstance(0).getFilterData(
              {
                hasEmpty: true,
                hasM2o: true
              }
            );
            const filterObj = {};
            filterData.forEach(el => {
              filterObj[el.field] = el.value;
            });
            config['tableConfig'] = Tsrv.utils.getM2OConfigOption(
              item.many2one.fields,
              filterObj
            );
          }
          Tsrv.utils
            .createModal('oMagicBox', {
              source: {
                funid: null,
                field: item.many2one.toTable,
                limit: 999
              },
              config
            })
            .then(data => {
              if (data && data.length > 0) {
                const msg = this.$Message.loading({
                  content: Tsrv.getI18nByPath('prompt.selbilling') as string,
                  duration: 0
                });
                data = data.map(el => {
                  return el.id;
                });
                const params = {
                  currentTable: this.name.tableNames[
                    Tsrv.utils.toNumber(this.currentTableIndex.split('_')[1])
                  ],
                  currentFunc: this.funName.formName,
                  currentFuncData: this.formData,
                  source: item.many2one.toTable,
                  data
                };
                params['getName'] = item.action;
                Tsrv.standardPostReq<ifs.I_queryRes<any>, any>(
                  params,
                  Tsrv.url.get
                )
                  .then(([res, err]) => {
                    this.$msg(res.msg ?? err);

                    if (res.success) {
                      const datas = Tsrv.utils.toStringJSON(
                        res.data.rows[0].FRtlJson
                      );

                      if (datas) {
                        this.needSave = true;

                        const formName: string = this.name.formName;
                        if (datas[formName]) {
                          this.forms.forEach((el: any, i: number) => {
                            const panelForm = this.GT_command.getFormInstance(
                              i
                            );
                            panelForm.clearValidate;

                            this.GT_command.getFormInstance(i).clearValidate();
                            for (const key in datas[formName][0]) {
                              panelForm.setFieldValue(
                                key,
                                datas[formName][0][key]
                              );
                            }
                          });
                        }

                        this.name.tableNames.forEach((name, idx) => {
                          if (datas[name]) {
                            datas[name].forEach(el => {
                              if (el.id) {
                                this.GT_command.getTableInstance(
                                  idx
                                ).setRowDataById(el.id, el);
                              } else {
                                this.GT_command.getTableInstance(
                                  index
                                ).insertRow(-1, {
                                  data: el
                                });
                              }
                            });
                          }
                        });
                        this.updateSaveBtnStatus();
                        this.$msg('50005,FE,0,');
                      }
                    } else {
                      this.$msg(Tsrv.getI18nByPath('warm.errBill'));
                    }
                  })
                  .catch(e => {
                    this.$msg(e);
                    console.error(e);
                  });
              }
            });
        } else {
          this.$msg(Tsrv.getI18nByPath('warm.plzSave'));
        }
      }
    }
  }

  private queryLinkClick(index: number, row: any = null) {
    if (index !== null) {
      const currentGrid = this.GT_command.getTableInstance(0);
      const formData = this.GT_command.getFormInstance(0).localData;

      const tableSelection = row || currentGrid.grid.getCurrentRecord();
      const item = this.config.queryLink[index];

      const searchCfg = [];
      item.children.forEach(el => {
        if (el.field.indexOf('.') > -1 && formData[el.field.split('.')[1]]) {
          searchCfg.push({
            field: el.toField,
            value: formData[el.field.split('.')[1]]
          });
        } else if (tableSelection[el.field]) {
          searchCfg.push({
            field: el.toField,
            value: tableSelection[el.field]
          });
        }
      });
      this.addTabFunc(item.funName).then((res: any) => {
        setTimeout(() => {
          if (
            res.$children[0].$children[0] &&
            typeof res.$children[0].$children[0].requestFilter === 'function'
          ) {
            res.$children[0].$children[0].requestFilter(searchCfg);
          }
        }, 0);
      });
    }
  }

  // 过账·取消过账
  private accountPost(value: boolean) {
    this.auditCheck('accountPost', value);
  }

  // 结案·反结案
  private caseclose(value: boolean) {
    this.auditCheck('caseclose', value);
  }

  // 冻结·解冻
  private freeze(value: boolean) {
    this.auditCheck('freeze', value);
  }

  // 作废
  private void() {
    this.auditCheck('void');
  }

  /**
   * reload
   */
  private reload(): Promise<boolean> {
    return new Promise(resolve => {
      if (!this.useTable) {
        this.GT_command.sendEventCoordination('refresh');
      }
      this.loadFormData(this.pageNo).then(res => {
        if (res !== undefined) {
          this.loadTableData().then(r => {
            if (r) {
              resolve(true);
            }
          });
          this.$emit('loadFormData', res);
          this.GT_command.editorState = EDIT_STATE.BROWSE;
          this.GT_command.getCustBtnStatus();
        }
        this.$msg('50003,FE,0,');
      });
    });
  }

  private handleAttachClicked() {
    const form = this.GT_command.getFormInstance(0);
    let value = {
      fileList: []
    };
    if (form.localData._file_) {
      value = Tsrv.utils.toStringJSON(form.localData._file_) || {
        fileList: []
      };
      this.openUploadFile(value);
    } else if (form.localData._file_info_id_) {
      Tsrv.utils.getFileInfoById(form.localData._file_info_id_).then(res => {
        if (res) {
          this.openUploadFile(res);
        } else {
          this.$msg(Tsrv.getI18nByPath('warm.noFileInfo'));
        }
      });
    } else {
      this.openUploadFile(value);
    }
  }

  private openUploadFile(value: any) {
    Tsrv.utils
      .createModal('o-file-manager', {
        limit: 100,
        upload: [],
        selected: Tsrv.utils.clone(value.fileList, true),
        action: value.fileList.length > 0 ? 'default' : 'file',
        hasCurrent: true,
        mode: this.toolbar.audit.value ? 'RDONLY' : 'DEFAULT'
      })
      .then(data => {
        if (data) {
          const list = {
            fileList: data
          };
          this.GT_command.getFormInstance(0).setFieldValue(
            // '_file_',
            '_file_info_id_',
            Tsrv.utils.toJSONString(list)
          );
          this.updateSaveBtnStatus();
        }
      });
  }

  // public auditCheck(value: boolean) {
  //   const title = value
  //     ? Tsrv.getI18nByPath('vxe.toolbar.audit')
  //     : Tsrv.getI18nByPath('vxe.toolbar.unaudit');
  //   const action = value ? '_sys_p_billAudit' : '_sys_p_billUnAudit';
  //   const params = {
  //     spName: action,
  //     pTableName: this.name.formName,
  //     pFunName: this.funName.formName,
  //     title: value ? 'audit' : 'unaudit',
  //     pMasterBillId: [this.formID]
  //   };
  //   if (!Tsrv.utils.isEmpty(this.formID)) {
  //     this.$Modal.confirm({
  //       title: Tsrv.getI18nBySrv(title),
  //       content: `${Tsrv.getI18nByPath('prompt.isExecute')}${Tsrv.getI18nBySrv(
  //         title
  //       )}`,
  //       onOk: () => {
  //         const loadMsg = this.$Message.loading({
  //           content: `${Tsrv.getI18nByPath(
  //             'prompt.execute'
  //           )}${Tsrv.getI18nBySrv(title)}...`,
  //           duration: 0
  //         });

  //         // Tsrv.standardPostReq<ifs.I_setDataRes, any>(params, Tsrv.url.fun)
  //         //   .then(([res, err]) => {
  //         //     // @ts-ignore
  //         //     loadMsg();
  //         //     this.$msg(err ?? res.msg);
  //         //     if (res.success) {
  //         //       this.updAuditState(value ? 'audit' : 'unAudit')
  //         //         .then(([b, _, er]) => {
  //         //           this.$msg(er ?? res.msg);
  //         //           if (b) {
  //         //             this.loadFormData(this.pageNo).then(res2 => {
  //         //               if (res2 !== undefined) this.loadTableData();
  //         //             });
  //         //           }
  //         //         })
  //         //         .catch(e => {
  //         //           console.error(e);
  //         //         });
  //         //     }
  //         //   })
  //         //   .catch(m => {
  //         //     // @ts-ignore
  //         //     loadMsg();
  //         //     console.error(m);
  //         //   });

  //         // 审核(取消审核)前事件（后封装公用方法）
  //         if (
  //           (action === '_sys_p_billAudit' &&
  //             !Tsrv.utils.noValue(this.actionsCfg.beforeAudit)) ||
  //           (action === '_sys_p_billUnAudit' &&
  //             !Tsrv.utils.noValue(this.actionsCfg.beforeUnaudit))
  //         ) {
  //           const p = this.GT_command.getSelectedData();
  //           const auditAction =
  //             action === '_sys_p_billAudit'
  //               ? this.actionsCfg.beforeAudit
  //               : this.actionsCfg.beforeUnaudit;
  //           if (auditAction) {
  //             this.GT_command.doEvent(auditAction, p)
  //               .then(r => {
  //                 this.doAudit(value, action, params, loadMsg);
  //               })
  //               .catch(err => {
  //                 console.error(err);
  //               });
  //           }
  //         } else {
  //           this.doAudit(value, action, params, loadMsg);
  //         }
  //       }
  //     });
  //   }
  // }

  // private doAudit(value, action, params, loadMsg) {
  //   this.GT_command.doEvent(action, params)
  //     .then(r => {
  //       // @ts-ignore
  //       loadMsg();
  //       if (r) {
  //         this.updAuditState(value ? 'audit' : 'unAudit')
  //           .then(([b, _, er]) => {
  //             // this.$msg(er ?? res.msg);
  //             if (b) {
  //               this.loadFormData(this.pageNo).then(res2 => {
  //                 if (res2 !== undefined) this.loadTableData();
  //               });
  //             }
  //             // 审核(取消审核)后事件
  //             if (
  //               (action === '_sys_p_billAudit' &&
  //                 !Tsrv.utils.noValue(this.actionsCfg.afterAudit)) ||
  //               (action === '_sys_p_billUnAudit' &&
  //                 !Tsrv.utils.noValue(this.actionsCfg.afterUnaudit))
  //             ) {
  //               const p = this.GT_command.getSelectedData();
  //               const auditAction =
  //                 action === '_sys_p_billAudit'
  //                   ? this.actionsCfg.afterAudit
  //                   : this.actionsCfg.afterUnaudit;
  //               if (auditAction) {
  //                 this.GT_command.doEvent(auditAction, p)
  //                   .then(resp => {})
  //                   .catch(err => {
  //                     console.error(err);
  //                   });
  //               }
  //             }
  //           })
  //           .catch(e => {
  //             console.error(e);
  //           });
  //         // if (r) {
  //         //   this.loadFormData(this.pageNo).then(res2 => {
  //         //     if (res2 !== undefined) this.loadTableData();
  //         //   });
  //         // }
  //         // // 审核(取消审核)后事件
  //         // if (
  //         //   (action === '_sys_p_billAudit' &&
  //         //     !Tsrv.utils.noValue(this.actionsCfg.afterAudit)) ||
  //         //   (action === '_sys_p_billUnAudit' &&
  //         //     !Tsrv.utils.noValue(this.actionsCfg.afterUnaudit))
  //         // ) {
  //         //   const p = this.GT_command.getSelectedData();
  //         //   const auditAction =
  //         //     action === '_sys_p_billAudit'
  //         //       ? this.actionsCfg.afterAudit
  //         //       : this.actionsCfg.afterUnaudit;
  //         //   if (auditAction) {
  //         //     this.GT_command.doEvent(auditAction, p)
  //         //       .then(resp => {})
  //         //       .catch(err => {
  //         //         console.error(err);
  //         //       });
  //         //   }
  //         // }
  //       }
  //     })
  //     .catch(err => {
  //       // @ts-ignore
  //       loadMsg();
  //       console.error(err);
  //     });
  // }

  // public updAuditState(
  //   s: 'audit' | 'unAudit'
  // ): Promise<[boolean, ifs.I_setDataRes, string]> {
  //   const rule = new ts.T_rule();
  //   const updD = new ts.T_ctdUpdData();
  //   updD.setFilter({ id: { $eq: this.formID } });
  //   updD.setRowData(
  //     { field: '_status_', value: s === 'audit' ? 101 : 0 } as ifs.I_fv,
  //     { field: '_audited_', value: s === 'audit' ? 1 : 0 } as ifs.I_fv
  //   );
  //   const upd = new ts.T_ctdUpdRec();
  //   upd.setCtdUpdData(updD);

  //   return Tsrv.updRows(
  //     this.name.formName,
  //     this.GT_command.getFormInstance(0).getDbType(),
  //     rule,
  //     upd
  //   );
  // }

  public auditCheck(
    type:
      | 'check'
      | 'accountPost'
      | 'caseclose'
      | 'freeze'
      | 'void'
      | 'requestAudit'
      | 'antiAudit',
    status: boolean = true
  ) {
    let befEvent: string | undefined;
    let aftEvent: string | undefined;
    switch (type) {
      case 'check': // 审核
        befEvent = status
          ? this.actionsCfg.beforeAudit
          : this.actionsCfg.beforeUnaudit;
        aftEvent = status
          ? this.actionsCfg.afterAudit
          : this.actionsCfg.afterUnaudit;
        break;
      case 'accountPost':
        befEvent = status
          ? this.actionsCfg.beforeAccountPosted
          : this.actionsCfg.beforeCancelPost;
        aftEvent = status
          ? this.actionsCfg.afterAccountPosted
          : this.actionsCfg.afterCancelPost;
        break;
      case 'caseclose':
        befEvent = status
          ? this.actionsCfg.beforeCaseclosed
          : this.actionsCfg.beforeAnticlosing;
        aftEvent = status
          ? this.actionsCfg.afterCaseclosed
          : this.actionsCfg.afterAnticlosing;
        break;
      case 'freeze': // 冻结
        befEvent = status
          ? this.actionsCfg.beforeFreeze
          : this.actionsCfg.beforeUnfreeze;
        aftEvent = status
          ? this.actionsCfg.afterFreeze
          : this.actionsCfg.afterUnfreeze;
        break;
      case 'void': // 作废
        befEvent = this.actionsCfg.beforeVoid;
        aftEvent = this.actionsCfg.afterVoid;
        break;
      case 'antiAudit': // 反审核
        befEvent = this.actionsCfg.beforeAntiaudit;
        aftEvent = this.actionsCfg.afterAntiaudit;
        break;
      default:
        break;
    }
    this.doAuditCheck(type, status, { befEvent, aftEvent })
      .then(([b, _, er]) => {
        if (b) {
          this.loadFormData(this.pageNo).then(res2 => {
            if (res2 !== undefined) this.loadTableData();
          });
        } else {
          this.$msg(er ?? er);
        }
      })
      .catch(e => {
        console.error(e);
      });
  }

  public doAuditCheck(
    type:
      | 'check'
      | 'accountPost'
      | 'caseclose'
      | 'freeze'
      | 'void'
      | 'requestAudit'
      | 'antiAudit',
    operate: boolean | undefined = undefined,
    events: any
  ): Promise<[boolean, ifs.I_setDataRes, string]> {
    const { befEvent, aftEvent } = events;
    let eventName: string = '';
    const rule = new ts.T_rule();
    const updD = new ts.T_ctdUpdData();
    updD.setFilter({ id: { $eq: this.formID } });
    const updataRecords: ifs.I_fv[] = [];
    switch (type) {
      case 'check': // 审核
        updataRecords.push(
          ...[
            { field: '_audited_', value: operate ? 1 : 0 } as ifs.I_fv,
            { field: '_status_', value: operate ? 101 : 0 } as ifs.I_fv
          ]
        );
        eventName = operate ? 'audit' : 'unaudit';
        break;
      case 'accountPost':
        updataRecords.push({
          field: '_status_',
          value: operate ? 200 : this.formData['_previous_status_']
        } as ifs.I_fv);
        eventName = operate ? 'accountPost' : 'cancelPost';
        break;
      case 'caseclose':
        updataRecords.push({
          field: '_status_',
          value: operate ? 300 : this.formData['_previous_status_']
        } as ifs.I_fv);
        eventName = operate ? 'caseclose' : 'anticlosing';
        break;
      case 'freeze': // 冻结
        updataRecords.push({
          field: '_status_',
          value: operate ? 999 : this.formData['_previous_status_']
        } as ifs.I_fv);
        eventName = operate ? 'freeze' : 'unfreeze';
        break;
      case 'void': // 作废
        updataRecords.push({
          field: '_status_',
          value: -1
        } as ifs.I_fv);
        eventName = 'void';
        break;
      case 'antiAudit': // 作废
        updataRecords.push(
          ...[
            { field: '_audited_', value: 0 } as ifs.I_fv,
            { field: '_status_', value: 100 } as ifs.I_fv
          ]
        );
        eventName = 'antiAudit';
        break;
      case 'requestAudit': // 作废
        updataRecords.push(
          ...[
            { field: '_audited_', value: 0 } as ifs.I_fv,
            { field: '_status_', value: 100 } as ifs.I_fv
          ]
        );
        // eventName = 'requestAudit';
        break;
      default:
        break;
    }
    updD.setRowData(...updataRecords);
    const upd = new ts.T_ctdUpdRec();
    upd.setCtdUpdData(updD);

    const p = this.GT_command.getSelectedData();

    if (befEvent) {
      const syncParams = new ts.T_syncParams();
      const _p = Tsrv.utils.clone(p, true);
      _p.from = `before${eventName}`;
      syncParams
        .setApiName(befEvent)
        .setUserInfo(Tsrv.getUserInfo() as ifs.I_userInfo)
        .setFunInfo(Tsrv.getFunInfo(this.funName.formName) as ifs.I_funInfo)
        .setSyncData(_p);
      upd.setBefEvent(syncParams);
    }
    if (aftEvent) {
      const syncParams = new ts.T_syncParams();
      const _p = Tsrv.utils.clone(p, true);
      _p.from = `after${eventName}`;
      syncParams
        .setApiName(aftEvent)
        .setUserInfo(Tsrv.getUserInfo() as ifs.I_userInfo)
        .setFunInfo(Tsrv.getFunInfo(this.funName.formName) as ifs.I_funInfo)
        .setSyncData(_p);
      upd.setAftEvent(syncParams);
    }

    return Tsrv.updRows(
      this.name.formName,
      this.GT_command.getFormInstance(0).getDbType(),
      rule,
      upd
    );
  }

  public delete() {
    if (this.isLoadEditLock) {
      if (this.GT_command.editLocked.has(this.formID)) {
        this.$msg('214,FE,11,Data locked');
      } else {
        this.dialogDel();
      }
    } else {
      this.GT_command.loadEditLock().then(b => {
        this.isLoadEditLock = b; // 取编辑锁的结果
        if (!b) {
          this.$msg(Tsrv.getI18nByValue('获取编辑锁失败'));
        } else {
          if (this.GT_command.editLocked.has(this.formID)) {
            this.$msg('214,FE,11,Data locked');
          } else {
            this.dialogDel();
          }
        }
      });
    }
  }

  private dialogDel() {
    this.$Modal.confirm({
      okText: Tsrv.getI18nByPath('others.ok') as string,
      cancelText: Tsrv.getI18nByPath('others.cancel') as string,
      title: Tsrv.getI18nByPath('prompt.isDeleteBill') as string,
      content: Tsrv.getI18nByPath('prompt.deleteData') as string,
      onOk: () => {
        this.beforeDelete();
      }
    });
  }

  private switchEdit(value: boolean) {
    if (value) {
      this.GT_command.editorState = EDIT_STATE.MODIFY;
      this.GT_command.loadEditLock().then(b => {
        this.isLoadEditLock = b; // 取编辑锁的结果
        if (!b) {
          this.$msg(Tsrv.getI18nByValue('获取编辑锁失败'));
        } else {
          if (!this.useTable) {
            this.GT_command.sendEventCoordination('edit');
          }
          this.GT_command.handleEditLock({ id: this.formID }, 'lock').then(
            ok => {
              if (ok) {
                this.GT_command.setModify(true);
              } else {
                this.$msg('214,FE,11,Data locked');
              }
            }
          );
        }
      });
    } else {
      if (!this.useTable) {
        this.GT_command.sendEventCoordination('unEdit');
      }
      this.GT_command.editorState = EDIT_STATE.BROWSE;
      this.GT_command.setModify(false);
      this.loadTableData();
      this.GT_command.unLockALL();
    }
  }

  public doPrint() {
    this.isOpenPrint = false;
    // const params = {
    //   funName: this.funName.formName,
    //   actionTitle: this.selectedPrintTemp,
    //   area: 'toolbar'
    // };

    // pmsCheck弃用
    // Tsrv.httpReqV1.pmsCheck(params).then((data: any) => {
    //   data = data.data;
    //   this.$msg(data.msg);
    //   if (data.success) {
    //     const ids = this.formID;
    //     const url = `${this.$config.reportURL}?_u=file:${encodeURI(
    //       encodeURI(this.selectedPrintTemp)
    //     )}&ids=${ids}`;
    //     window.open(url, '_blank');
    //   }
    // });

    const printSrv: number = this.selectedPrintTemp['report_servers'];
    const reportID: string = this.selectedPrintTemp['f_code'];
    if (printSrv === 0) {
      const ids = this.formID;
      const url = `${this.$config.reportURL}view/${reportID}?ids=${ids}&token=${
        Tsrv.getStore().getters.Token
      }`;
      window.open(url);
    }
  }

  private loadData() {
    this.loadFormData(this.pageNo).then(res => {
      if (this.pageNo === 1) {
        this.toolbar.next.isDisable = false;
        this.toolbar.jumpLast.isDisable = false;
      }
      if (res !== undefined) {
        this.$emit('loadFormData', res);
        this.loadTableData();
      }
    });
  }

  /**
   * 打印
   */
  public print() {
    this.isOpenPrint = true;
  }

  private receiveBaseFormDataPkg(e) {
    // ??? 没有 'focus', 'blur' ???
    // const allowEvents = ['dochange', 'enter', 'mouseenter', 'mouseleave'];
    const allowEvents = [
      'dochange',
      'enter',
      'mouseenter',
      'mouseleave',
      'focus',
      'blur'
    ];
    // const p = e.data.params;
    const p = e.data;
    if (e.eventType === 'input') {
      const data = {};
      data[p.property] = p.data[p.property];
      this.setTabelM2o(data);

      for (const key in p.data) {
        this.formData[key] = p.data[key];
      }
    } else if (
      allowEvents.indexOf(e.eventType) > -1 &&
      !Tsrv.utils.isEmpty(e.tableName) &&
      !Tsrv.utils.isEmpty(e.funName)
    ) {
      this.updateSaveBtnStatus();

      // let action = [];
      // // for (let i = 0; i < p.$form.items.length; i++) {
      // // if (p.$form.items[i].field === p.property) {
      // // const attrs = p.$form.items[i].itemRender.attrs;
      // for (let i = 0; i < e.data.$form.items.length; i++) {
      //   if (e.data.$form.items[i].field === p.property) {
      //     const attrs = e.data.$form.items[i].itemRender.attrs;
      //     if (attrs['actions']) {
      //       action = attrs['actions'].dochange;
      //     }
      //     break;
      //   }
      // }
      // if (action) {
      //   const params = {
      //     pFuncName: '_sys_p_fieldCalc',
      //     pCalcField: p.property,
      //     pData: [
      //       {
      //         sTableName: e.tableName,
      //         sFuncName: e.funName,
      //         iCalcTable: 1,
      //         sTableData: this.GT_command.getFormInstance(0).localData
      //       }
      //     ]
      //   };
      //   Tsrv.httpReqV1.vce(params).then(res => {
      //     res = res.data;
      //     if (res.success) {
      //       Object.keys(res.data.data).forEach(key => {
      //         if (key.indexOf('.') > -1) {
      //           const field = key.split('.')[1];
      //           e.obj.setFieldValue(field, res.data.data[key]);
      //           p.$form.data[field] = res.data.data[key];
      //         }
      //       });
      //     }
      //   });
      // }
      let actions = [];
      for (let i = 0; i < e.data.$form.items.length; i++) {
        if (e.data.$form.items[i].field === p.property) {
          const attrs = e.data.$form.items[i].itemRender.attrs;
          if (attrs['actions']) {
            actions = attrs['actions'];
          }
          break;
        }
      }
      if (!Tsrv.utils.noValue(e.eventType) && !Tsrv.utils.noValue(actions)) {
        const action = Tsrv.utils.find(
          actions,
          item => item.eventType === e.eventType
        );
        if (!Tsrv.utils.noValue(action) && !Tsrv.utils.noValue(action.pubApi)) {
          const params = {
            funName: e.tableName,
            title: e.data.property, //
            from: 'fieldEvent',
            data: {
              [Tsrv.globalVar.fieldName.ID]: e.data.data.id,
              rowData: e.data.data,
              [e.data.property]: e.data.data[e.data.property]
            },
            parentID: 0
          };
          this.GT_command.doEvent(action.pubApi, params, { fieldData: e });
        }
      }
    }
  }

  private receiveBaseGridDataPkg(e) {
    // 注：dochange 与 focus blur 可能有重复使用的地方 - 需在input组件中检查过滤
    // 'focus', 'blur' 事件
    const allowEvents = [
      'dochange',
      'enter',
      'mouseenter',
      'mouseleave',
      'focus',
      'blur'
    ];
    if (
      allowEvents.indexOf(e.eventType) > -1 &&
      !Tsrv.utils.isEmpty(e.tableName) &&
      !Tsrv.utils.isEmpty(e.funName)
    ) {
      this.updateSaveBtnStatus();
      // let action;
      // if (e.data?.column?.editRender?.attrs['actions']) {
      //   action = e.data.column.editRender.attrs['actions'].dochange;
      // }
      // if (action) {
      //   const params = {
      //     pFuncName: '_sys_p_fieldCalc',
      //     pCalcField: e.data.column.property,
      //     pData: [
      //       {
      //         sTableName: this.name.formName,
      //         sFuncName: this.funName.formName,
      //         iCalcTable: 0,
      //         sTableData: this.GT_command.getFormInstance(0).localData
      //       },
      //       {
      //         sTableName: e.tableName,
      //         sFuncName: this.funName.formName,
      //         iCalcTable: 1,
      //         sTableData: e.data.row
      //       }
      //     ]
      //   };
      //   Tsrv.httpReqV1.vce(params).then(res => {
      //     res = res.data;
      //     if (res.success) {
      //       const fullData = e.data.$table.getTableData().fullData;
      //       Object.keys(res.data.data).forEach(key => {
      //         if (key.indexOf('.') > -1) {
      //           const field = key.split('.')[1];
      //           for (let i = 0; i < fullData.length; i++) {
      //             if (fullData[i]._XID === e.data.row._XID) {
      //               fullData[i][field] = res.data.data[key];
      //               e.data.$table.updateData();
      //               break;
      //             }
      //           }
      //         }
      //       });
      //     }
      //   });
      // }
      let actions = [];
      if (e.data?.column?.editRender?.attrs['actions']) {
        actions = e.data.column.editRender.attrs['actions'];
      }
      if (!Tsrv.utils.noValue(e.eventType) && !Tsrv.utils.noValue(actions)) {
        const action = Tsrv.utils.find(
          actions,
          item => item.eventType === e.eventType
        );
        if (!Tsrv.utils.noValue(action) && !Tsrv.utils.noValue(action.pubApi)) {
          const field = e.data.column.property;
          // if (field.indexOf('|') && !Tsrv.noValue(field.split('|')[1])) {
          //   field = field.split('|')[1];
          // }
          const params = {
            funName: e.tableName,
            title: field, //
            from: 'fieldEvent',
            data: {
              primary_order__id: this.formID,
              rowData: e.data.row,
              [Tsrv.globalVar.fieldName.ID]: e.data.row.id,
              [field]: e.data.row[field]
            },
            // parentID: this.linkParent.rowID || 0
            parentID: 0
          };
          this.GT_command.doEvent(action.pubApi, params, { fieldData: e });
        }
      }
    }
  }

  private setTabelM2o(data: any) {
    const autoCompleteInfo = {
      key: this.formID,
      table: this.name.formName,
      data
    };
    const option = {
      isAsFilter: true,
      isReload: false,
      isOverwrite: true,
      isSetScope: true
    };
    this.name.tableNames.forEach((name, index) => {
      this.GT_command.getTableInstance(index).setAutoComplete(
        autoCompleteInfo,
        option
      );
    });
  }

  /**
   * 加载表体数据
   */
  private loadTableData(): Promise<boolean> {
    return new Promise(resolve => {
      if (!this.useTable) {
        return;
      }
      this.GT_command.unLockALL();
      if (!Tsrv.utils.isEmpty(this.formID)) {
        // 查所属的所有表，建立m2o对应关系
        const autoCompleteInfo = {
          key: this.formID,
          table: this.name.formName,
          data: this.formData
        };
        const option = {
          isAsFilter: true,
          isReload: false,
          isSetScope: true
        };
        const promiseQueue = [];
        this.name.tableNames.forEach((name, index) => {
          promiseQueue.push(
            this.GT_command.getTableInstance(index).setAutoComplete(
              autoCompleteInfo,
              option
            )
          );
        });
        Promise.all(promiseQueue).then(() => {
          const loadQueue = [];
          this.name.tableNames.forEach((name, index) => {
            loadQueue.push(
              this.GT_command.getTableInstance(index).loadTableData()
            );
          });
          Promise.all(loadQueue)
            .then(() => {
              // this.updateSaveBtnStatus();
              this.toolbar.save.isDisable = true;
              this.GT_command.editorState = EDIT_STATE.BROWSE; // 设置编辑状态
              resolve(true);
            })
            .catch(() => {
              this.$msg(Tsrv.getI18nByPath('prompt.noTableBody'));
            });
        });
      }
    });
  }

  private doSearchResHandle(res: ifs.I_queryResData<any>): Promise<void> {
    const that = this;
    return new Promise(resole => {
      that.total = 2;
      that.isNew = false;

      that.GT_command.setModify(false);
      this.GT_command.setLoadForomDataBtnState();
      for (let i = 0; i < that.formsLength; i++) {
        that.GT_command.getFormInstance(i).clearValidate();
        that.GT_command.getFormInstance(i).setFormData(that.formData);
      }
      setTimeout(() => {
        that.updateSaveBtnStatus();
        resole();
      }, 0);
    });
  }

  private doNotSearchResHandle(res: ifs.I_queryResData<any>): Promise<Object> {
    const that = this;
    return new Promise(resole => {
      if (res.rows.length === 0) {
        // 如果form没有数据，则为新建状态
        that.insert();
        for (let i = 0; i < that.formsLength; i++) {
          that.GT_command.getFormInstance(0).clearValidate();
        }
        setTimeout(() => {
          that.updateSaveBtnStatus();
        }, 0);
        resole(undefined);
      } else {
        // 获取formID
        that.total = res.total;
        that.isNew = false;

        that.GT_command.setModify(false);
        this.GT_command.setLoadForomDataBtnState();
        if (that.toolbar.selbill) that.toolbar.selbill.isDisable = false;
        that.formID = res.rows[0] ? res.rows[0].id : -1;
        that.formData = res.rows[0] || {};
        for (let i = 0; i < that.forms.length; i++) {
          that.GT_command.getFormInstance(i).clearValidate();
          that.GT_command.getFormInstance(i).setFormData(that.formData);
        }
        that.updateAuditStatus(res.rows[0]);
        setTimeout(() => {
          that.updateSaveBtnStatus();
          resole(this.formData);
        }, 0);
      }
    });
  }

  // 加载form数据
  private loadFormData(pageNo = 1, filter?: ifs.I_fv[]): Promise<Object> {
    this.GT_command.unLockALL();
    const that = this;
    return new Promise(resolve => {
      if (this.GT_command.getFormInstance(0)) {
        that.toolbar.edit.value = false;
        that.toolbar.delete.isDisable = false;
        // 如果存在filter，则为搜索结果点击导致的加载数据
        // if (filter) {
        //   // that.pageNo = 0;
        //   that.pageNo = 1;
        //   that.toolbar.next.isDisable = false;
        //   that.toolbar.jumpLast.isDisable = false;
        //   that.toolbar.previous.isDisable = true;
        //   that.toolbar.jumpFirst.isDisable = true;
        //   pageNo = 1;
        // }
        // 清除验证格式
        that.GT_command.getFormInstance(0).clearValidate();
        // 重新加载表
        that.GT_command.getFormInstance(0)
          .loadFormData(pageNo, filter)
          .then(res => {
            if (res.total === 0 || !res) {
              that.toolbar.insert.isDisable = false;
              resolve(undefined);
            } else if (res.total > 1) {
              that.toolbar.next.isDisable = false;
              that.toolbar.jumpLast.isDisable = false;
            }
            that.needSave = false;
            if (filter) {
              // 如果为搜索结果
              // this.doSearchResHandle(res).then(r => {
              //   that.formID = res.rows[0] ? res.rows[0].id : -1;
              //   // 将其他表设置数据
              //   that.formData = res.rows[0] || {};
              //   resolve(that.formData);
              // });

              // 修改后（doSearchResHandle 函数待理解）
              this.doSearchResHandleReplace(res).then(resp => {
                resolve(resp);
              });
            } else {
              this.doNotSearchResHandle(res).then(resp => {
                // this.$emit('loadFormData', resp);
                resolve(resp);
              });
            }
            this.pageNo === 0 && (this.pageNo = 1);
          });
      } else {
        resolve(undefined);
      }
    });
  }

  // 存在 过滤条件 情况 （待完善）
  private doSearchResHandleReplace(
    res: ifs.I_queryResData<any>
  ): Promise<Object> {
    const that = this;
    return new Promise(resole => {
      if (res.rows.length === 0) {
        // for (let i = 0; i < that.formsLength; i++) {
        //   that.GT_command.getFormInstance(i).clearValidate();
        // }
        setTimeout(() => {
          that.updateSaveBtnStatus();
        }, 0);
        this.loadFormData();
        resole(undefined);
      } else {
        // 获取formID
        that.total = res.total;
        that.isNew = false;

        that.GT_command.setModify(false);
        this.GT_command.setLoadForomDataBtnState();
        if (that.toolbar.selbill) that.toolbar.selbill.isDisable = false;
        that.formID = res.rows[0] ? res.rows[0].id : -1;
        that.formData = res.rows[0] || {};
        for (let i = 0; i < that.forms.length; i++) {
          that.GT_command.getFormInstance(i).clearValidate();
          that.GT_command.getFormInstance(i).setFormData(that.formData);
        }
        that.updateAuditStatus(res.rows[0]);
        setTimeout(() => {
          that.updateSaveBtnStatus();
          resole(this.formData);
        }, 0);
      }
    });
  }

  private updateAuditStatus(row: any) {
    const status = row['_audited_'];
    const billStatus = row['_status_'];
    // this.hasRequestAudit
    if (!Tsrv.utils.noValue(billStatus) && !Tsrv.utils.noValue(status)) {
      this.toolbar.audit.value = status === 1;
      this.toolbar.requestAudit.value = status === 1 && billStatus === 101;
      this.toolbar.accountPosted.value = billStatus === 200;
      this.toolbar.caseclosed.value = billStatus === 300;
      this.toolbar.freeze.value = billStatus === 999;
      if (status === 1) {
        this.toolbar.audit.value = true;
        this.toolbar.unaudit.auth = true;
        // 审核相关按钮 状态
        this.toolbar.audit.isDisable = !(
          billStatus === 0 || billStatus === 101
        );
      } else {
        this.toolbar.audit.value = false;
        // 审核相关按钮 状态
        this.toolbar.audit.isDisable = !(
          billStatus === 0 || billStatus === 101
        );
      }
      this.toolbar.requestAudit.isDisable = !(
        (status === 0 && billStatus === 0) ||
        (status === 1 && billStatus === 101)
      );
      this.toolbar.auditStatus.isDisable = !(
        status === 0 && billStatus === 100
      );
      this.toolbar.accountPosted.isDisable = !(
        status === 1 &&
        (billStatus === 101 || billStatus === 200)
      );
      this.toolbar.caseclosed.isDisable = !(
        status === 1 &&
        (billStatus === 101 || billStatus === 200 || billStatus === 300)
      );
      this.toolbar.freeze.isDisable =
        billStatus === -1 || billStatus === 200 || billStatus === 300;
      this.toolbar.void.isDisable = billStatus >= 200 || billStatus === -1;
      // 根据 单据状态 决定 显示的标签内容
      Object.keys(this.tagsControl).forEach(key => {
        this.tagsControl[key] = false;
      });
      if (billStatus === 100) {
        this.tagsControl.approval = true;
      } else if (billStatus === 101) {
        status === 1 && (this.tagsControl.audit = true);
      } else if (billStatus === 200) {
        this.tagsControl.accountPosted = true;
      } else if (billStatus === 300) {
        this.tagsControl.caseclosed = true;
      } else if (billStatus === 999) {
        this.tagsControl.freeze = true;
      } else if (billStatus === -1) {
        this.tagsControl.void = true;
      }
      // 根据 单据审核状态 决定 除审核相关的标准按钮 状态
      if (status === 1 || billStatus !== 0) {
        this.toolbar.edit.isDisable = true;
        this.toolbar.delete.isDisable = true;
        // this.toolbar.requestAudit.isDisable = true;
        if (this.toolbar.selbill) this.toolbar.selbill.isDisable = true;
      }
      // 判断是否是显示正常状态
      let isNormal = true;
      Object.keys(this.tagsControl).forEach(key => {
        if (key !== 'normal' && this.tagsControl[key]) {
          isNormal = false;
        }
      });
      this.tagsControl.normal = isNormal;
    } else {
      // 关闭关于审核的业务按钮
      this.toolbar.requestAudit.isShow = false;
      this.toolbar.antiAudit.isShow = false;
      this.toolbar.auditStatus.isShow = false;
      this.toolbar.audit.isShow = false;
      this.toolbar.unaudit.isShow = false;
      this.toolbar.accountPosted.isShow = false;
      this.toolbar.cancelPost.isShow = false;
      this.toolbar.caseclosed.isShow = false;
      this.toolbar.anticlosing.isShow = false;
      this.toolbar.freeze.isShow = false;
      this.toolbar.unfreeze.isShow = false;
      this.toolbar.void.isShow = false;
      this.tagsControl.audit = false; // 审核标签
      this.tagsControl.normal = true;
    }
  }

  private getRecordIndexById(id: string) {
    return new Promise((resolve, reject) => {
      const form = this.GT_command.getFormInstance(0);
      form
        .getRecordIndexById(id)
        .then(res => {
          resolve(res);
        })
        .catch(() => {
          reject();
        });
    });
  }

  public getRecordById(id: string) {
    this.loadFormData(1, [{ field: 'id', value: `${id}` }] as ifs.I_fv[]).then(
      res => {
        if (res !== undefined) {
          this.$emit('loadFormData', res);
          this.loadTableData();
        }
      }
    );
  }

  /**
   * 新建单据
   */
  private insert() {
    if (this.GT_command.editorState !== EDIT_STATE.NEW) {
      this.GT_command.editorState = EDIT_STATE.NEW;
      this.formID = 0;
      this.pageNo = 0;
      // toolbar设置
      this.GT_command.setInsertBtnState();

      // 可编辑
      this.GT_command.setModify(true);
      // 清空数据
      this.clearData();
      this.formID = Tsrv.getSnowIDFmtStr();
      this.formData['id'] = this.formID;
      this.setTabelM2o(this.GT_command.getFormInstance(0).localData);
    }
  }

  private validate() {
    const promiseList = [];
    for (let i = 0; i < this.GT_command.formsNum; i++) {
      promiseList.push(this.GT_command.getFormInstance(i).validate());
    }
    this.name.tableNames.forEach((name, index) => {
      promiseList.push(this.GT_command.getTableInstance(index).validate(true));
    });
    return Promise.all(promiseList);
  }

  private doActions(action: string, params: any) {
    return new Promise((resolve, reject) => {
      params['spName'] = action;
      Tsrv.standardPostReq<ifs.I_setDataRes, any>(params, Tsrv.url.fun)
        .then(([res, err]) => {
          if (res.success) {
            resolve(true);
          } else {
            this.$msg(res.data.msg);
            reject();
          }
        })
        .catch(e => {
          this.oBaseGrid.$msg(e);
          console.error(e);
        });
    });
  }

  /**
   * 清除数据
   */
  public clearData() {
    // 重置所有表头
    for (let i = 0; i < this.GT_command.formsNum; i++) {
      const form = this.GT_command.getFormInstance(i);
      form.clearFormData().then(() => {
        const TdevVal = new ts.T_defVal();
        TdevVal.setLang(this.$i18n.locale)
          .setDbType('mysql')
          .setFunName(this.funName.formName);
        // TdevVal.setMainfunName(this.linkParent.mainFunName).setRowID(
        //   this.linkParent.rowID
        // );
        Tsrv.getDefaultVal(TdevVal).then(r => {
          for (const o of r) {
            form.setFieldValue(o.field, o.value);
          }
        });
      });
    }

    // 重置所有表体
    this.name.tableNames.forEach((name, index) => {
      const table = this.GT_command.getTableInstance(index);
      const options = {
        resetM2O: true,
        resetSLC: true
      };
      table.clearTableData(options);
      // .then(() => {
      //   table.insertRow(null, {
      //     active: false
      //   });
      // });
    });
  }

  /**
   * 保存前
   */
  private save() {
    this.validate()
      .then((res: Array<any>) => {
        const failure = [];
        res.forEach(vali => {
          if (!Tsrv.noValue(vali)) {
            failure.push(vali);
          }
        });
        if (failure.length > 0) {
          const failureFields = [];
          failure.forEach(vali => {
            Object.keys(vali).forEach(field => {
              if (field.startsWith('m2o|') || field.startsWith('slc|')) {
                failureFields.push(
                  Tsrv.getI18nBySrv(field.split('|')[1]) as string
                );
              } else {
                failureFields.push(Tsrv.getI18nBySrv(field) as string);
              }
            });
          });
          this.$Message.warning(
            Tsrv.getI18nByValue(
              `校验不通过！请仔细检查字段：${failureFields.join('、')}`
            ) as string
          );
          return;
        }
        if (this.loading === false) {
          this.loading = true;
          const msg = this.$Message.loading({
            content: Tsrv.getI18nByPath('prompt.saving') as string,
            duration: 0
          });
          this.bpaStaging = Tsrv.utils.clone(this.GT_command.getBpa(), true);
          this.doSave()
            .then(() => {
              if (!this.useTable) {
                this.GT_command.sendEventCoordination('save');
              }
              // @ts-ignore
              msg();
              this.loading = false;
              // this.GT_command.editorState = EDIT_STATE.BROWSE;
            })
            .catch(() => {
              // @ts-ignore
              msg();
              this.loading = false;
              // this.GT_command.editorState = EDIT_STATE.BROWSE;
            });
        }
      })
      .catch(() => {
        this.loading = false;
        this.$msg(Tsrv.getI18nByPath('warm.tableFormatIncorrect'));
      });
  }

  /**
   * 保存操作
   */
  private doSave(): Promise<boolean> {
    const bpa = this.GT_command.getBpa();
    return new Promise((resolve, reject) => {
      Tsrv.batBill(bpa).then(([b, res, msg]) => {
        if (!msg) {
          this.$msg(msg);
          reject(false);
        }
        if (!b) {
          this.$msg(res.msg);
          resolve(false);
        } else {
          this.needSave = false;
          if (this.pageNo === 0) this.pageNo = 1;
          this.loadData();
          if (
            this.searchControl.isSearchOpen &&
            !Tsrv.noValue(this.searchForms)
          ) {
            this.doSimpleSearch();
          }
          this.toolbar.save.isDisable = true;
          this.GT_command.editorState = EDIT_STATE.BROWSE;
          resolve(true);
        }
        // this.needSave = false;
        // if (this.pageNo === 0) this.pageNo = 1;
        // this.loadData();
        // this.toolbar.save.isDisable = true;
        // this.GT_command.editorState = EDIT_STATE.BROWSE;
        // resolve(true);
      });
    });
  }

  /**
   * 删除前
   */
  private beforeDelete() {
    if (this.GT_command.editorState === EDIT_STATE.NEW) {
      this.pageNo = 1;
      this.loadData();
      this.toolbar.next.isDisable = false;
      this.toolbar.jumpLast.isDisable = false;
    } else {
      this.GT_command.editorState = EDIT_STATE.DELETE;
      if (this.loading === false) {
        this.loading = true;
        const msg = this.$Message.loading({
          content: Tsrv.getI18nByPath('prompt.deleting') as string,
          duration: 0
        });
        this.doDelete()
          .then(() => {
            // @ts-ignore
            msg();
            this.loading = false;
          })
          .catch(() => {
            // @ts-ignore
            msg();
            this.loading = false;
          });
        // if (this.actionsCfg.beforeDelete) {
        //   this.doActions(
        //     this.actionsCfg.beforeDelete,
        //     this.getBeforeDeleteData()
        //   )
        //     .then(() => {
        //       this.doDelete()
        //         .then(() => {
        //           // @ts-ignore
        //           msg();
        //           this.loading = false;
        //         })
        //         .catch(() => {
        //           // @ts-ignore
        //           msg();
        //           this.loading = false;
        //         });
        //     })
        //     .catch(() => {
        //       // @ts-ignore
        //       msg();
        //       this.loading = false;
        //     });
        // } else {
        //   this.doDelete()
        //     .then(() => {
        //       this.loading = false;
        //       // @ts-ignore
        //       msg();
        //     })
        //     .catch(() => {
        //       this.loading = false;
        //       // @ts-ignore
        //       msg();
        //     });
        // }
      }
    }
  }

  /**
   * 删除操作
   */
  private doDelete() {
    return new Promise((resolve, reject) => {
      let afterExecRule: ifs.I_execRule;
      if (this.actionsCfg.afterDelete) {
        afterExecRule = new ts.T_execRule();
        afterExecRule.name = this.actionsCfg.afterDelete;
        afterExecRule.isDbTransactions = true;
        afterExecRule.inArg.push({
          name: 'params',
          dataType: 'object',
          value: this.getAfterDeleteData()
        });
      }
      const rule = new ts.T_rule();
      // if (!Tsrv.utils.noValue(afterExecRule)) {
      //   rule.setAfterExecRule(afterExecRule);
      // }
      const o = new ts.T_delbpaArg();
      const bpaHead = this.GT_command.getBpaHead();
      o.head.dbType = bpaHead.getDbType();
      o.head.funName = bpaHead.getFunName();
      o.head.removeRecords = bpaHead.removeRecords;
      o.head.rule = rule;
      Tsrv.delBill(o)
        .then(([b, res, err]) => {
          const m = err;
          !err && this.$msg(m);
          !b && this.$msg(res.msg);
          (!b || !err) && reject();
          // 如果删除最后一页，则加载上一页
          const pageNo =
            this.pageNo === this.total ? this.total - 1 : this.pageNo;
          this.pageNo = pageNo;
          // this.loadFormData(this.pageNo).then(r => {
          this.loadFormData(pageNo).then(r => {
            if (r !== undefined) {
              this.loadTableData();
              this.$emit('loadFormData', res);
              if (
                this.searchControl.isSearchOpen &&
                !Tsrv.noValue(this.searchForms)
              ) {
                this.doSimpleSearch();
              }
            }
          });
          resolve(true);
        })
        .catch(r => {
          reject();
        });
    });
  }

  /**
   * 更新保存按钮状态
   */
  private updateSaveBtnStatus() {
    this.GT_command.setSaveState();
  }

  /**
   * 获取保存前数据
   */
  private getBeforeSaveData() {
    const res = [];
    res.push({
      sTableName: this.name.formName,
      sFuncName: this.funName.formName,
      isMainTable: 1,
      sTableData: {
        insertRecords:
          this.GT_command.editorState === EDIT_STATE.NEW ? this.formData : {},
        updateRecords:
          this.GT_command.editorState === EDIT_STATE.NEW ? {} : this.formData,
        removeRecords: []
      }
    });
    this.name.tableNames.forEach((name, index) => {
      const changes = this.GT_command.getTableInstance(
        index
      ).grid.getRecordset();
      res.push({
        sTableName: name,
        sFuncName: this.funName.tableNames[index],
        isMainTable: 0,
        sTableData: {
          insertRecords: changes.insertRecords,
          updateRecords: changes.updateRecords,
          removeRecords: changes.removeRecords
        }
      });
    });
    return res;
  }

  /**
   * 获取保存后数据
   */
  private getAfterSaveData() {
    // 注：头和体不止一个
    const res = [];
    // res.push({
    //   sTableName: this.name.formName,
    //   sFuncName: this.funName.formName,
    //   isMainTable: 1,
    //   sTableData: {
    //     insertRecords:
    //       this.GT_command.editorState === EDIT_STATE.NEW
    //         ? this.formData['FGUID']
    //         : {},
    //     updateRecords:
    //       this.GT_command.editorState === EDIT_STATE.NEW
    //         ? {}
    //         : this.formData['FGUID'],
    //     removeRecords: {}
    //   }
    // });
    // this.name.tableNames.forEach((name, index) => {
    //   const changes = this.GT_command.getTableInstance(
    //     index
    //   ).grid.getRecordset();
    //   res.push({
    //     sTableName: name,
    //     sFuncName: this.funName.tableNames[index],
    //     isMainTable: 0,
    //     sTableData: {
    //       insertRecords: changes.insertRecords.map(el => {
    //         return el.FGUID;
    //       }),
    //       updateRecords: changes.updateRecords.map(el => {
    //         return el.FGUID;
    //       }),
    //       removeRecords: changes.removeRecords.map(el => {
    //         return el.FGUID;
    //       })
    //     }
    //   });
    // });
    // 改：
    const changes = Tsrv.utils.clone(this.bpaStaging, true);
    res.push({
      sTableName: changes.head.tableName,
      sFuncName: changes.head.funName,
      isMainTable: 0,
      sTableData: {
        insertRecords:
          this.GT_command.editorState === EDIT_STATE.BROWSE &&
          !Tsrv.utils.noValue(changes.head.insertRecords?.rowData)
            ? // ? changes.head.insertRecords.rowData
              changes.head.insertRecords
            : {},
        updateRecords:
          this.GT_command.editorState === EDIT_STATE.BROWSE &&
          !Tsrv.utils.noValue(changes.head.updateRecords?.rowData)
            ? // ? changes.head.updateRecords.rowData
              changes.head.updateRecords
            : {},
        removeRecords:
          this.GT_command.editorState === EDIT_STATE.BROWSE &&
          !Tsrv.utils.noValue(changes.head.removeRecords?.rowData)
            ? // ? changes.head.updateRecords.filter
              changes.head.updateRecords
            : {}
      }
    });
    changes.body.data.forEach((table, index) => {
      res.push({
        sTableName: table.tableName,
        sFuncName: changes.head.funName,
        isMainTable: 0,
        sTableData: {
          insertRecords: !Tsrv.utils.noValue(table.insertRecords?.data)
            ? // ? table.insertRecords.data
              table.insertRecords
            : {},
          updateRecords: !Tsrv.utils.noValue(table.updateRecords?.data)
            ? // ? table.updateRecords.data.filter(item => {
              //     return { filter: item.filter, rowData: item.rowData };
              //   })
              table.updateRecords
            : {},
          removeRecords: !Tsrv.utils.noValue(table.removeRecords?.data)
            ? // ? table.removeRecords.filter
              table.removeRecords
            : {}
        }
      });
    });
    return {
      data: res
    };
  }

  /**
   * 获取删除前数据
   */
  private getBeforeDeleteData() {
    const obj = {
      sTableName: this.name.formName,
      sFuncName: this.funName.formName,
      isMainTable: 1,
      sTableData: {
        insertRecords: {},
        updateRecords: {},
        removeRecords: this.formData['FGUID']
      }
    };
    return { data: [obj] };
  }

  /**
   * 获取删除后数据
   */
  private getAfterDeleteData() {
    const obj = {
      sTableName: this.name.formName,
      sFuncName: this.funName.formName,
      isMainTable: 1,
      sTableData: {
        insertRecords: {},
        updateRecords: {},
        removeRecords: this.formData
      }
    };
    return { data: [obj] };
  }

  /**
   * 获取单据功能ID
   */
  private getFunId() {
    return this.funID;
  }

  /**
   * 获取单据功能ID
   */
  private getFormData() {
    return this.formData;
  }

  /**
   * 执行自定义功能
   */
  public doCustomBtnAction(title: string, action: string, params?: any) {
    if (Tsrv.noValue(params)) {
      params = this.GT_command.getSelectedData();
      params.title = title;
      params.from = 'customButton';
    }

    this.GT_command.doEvent(action, params)
      .then(r => {})
      .catch(err => {
        console.error(err);
      });
  }
  /**
   * 执行控件事件
   */
  // public doOControlAction(action: string, field: string) {
  //   const params =  {
  //     funName: this.funName.formName,
  //     title: '',
  //     from: 'oControl',
  //     data: {
  //       rows: {}
  //     }
  //   };
  //   params.data[this.name.formName] = this.formID;
  //   this.name.tableNames.forEach((name, idx) => {
  //     const row = this.GT_command.getTableInstance(idx)
  //       .grid.getCurrentRecord();
  //     params.data[name] = row;
  //     params.data.rows[name] = row;
  //   });

  //   params.data['custBtns'] = [];
  //   this.toolbar['addon'].forEach(el => {
  //     params.data['custBtns'].push({ title: el.title, status: el.auth });
  //   });

  //   this.GT_command.doEvent(action, params)
  //     .then(r => {})
  //     .catch(err => {
  //       console.error(err);
  //     });
  // }

  /**
   * 加载某一页数据
   */
  public handleSearchTo(index: number) {
    return new Promise((resolve, reject) => {
      this.pageNo = index;
      this.loadFormData(index).then(res => {
        if (res !== undefined) {
          this.loadTableData();
          this.$emit('loadFormData', res);
          resolve(true);
        }
      });
    });
  }

  /**
   * 上一页
   */
  public prev() {
    if (this.pageNo > 1) {
      vxeConfig.form
        .jumpTo(-1, this.pageNo, this.total, this.toolbar)
        .then((current: number) => {
          this.pageNo = current;
          this.loadData();
        });
    }
  }

  /**
   * 下一页
   */
  private next() {
    if (this.pageNo !== this.total) {
      vxeConfig.form
        .jumpTo(null, this.pageNo, this.total, this.toolbar)
        .then((current: number) => {
          this.pageNo = current;
          this.loadData();
        });
    }
  }

  /**
   * 跳页
   */
  public jumpTo(to: number) {
    vxeConfig.form
      .jumpTo(to, this.pageNo, this.total, this.toolbar)
      .then((current: number) => {
        this.pageNo = current;
        this.loadData();
      });
  }

  /**
   * 尾页
   */
  public end() {
    vxeConfig.form
      .jumpTo(this.total, this.pageNo, this.total, this.toolbar)
      .then((current: number) => {
        this.pageNo = current;
        this.loadData();
      });
  }

  /**
   * 起始页
   */
  public start() {
    vxeConfig.form
      .jumpTo(1, this.pageNo, this.total, this.toolbar)
      .then((current: number) => {
        this.pageNo = current;
        this.loadData();
      });
  }

  public cleanSubCompData(
    p: N_oSetupPanel.N_comps.T_eventCoordinationToolbar
  ) {}

  /**
   * @description: 执行功能的自定义事件
   * @return {*}
   * @author: swc
   * @Date: 2024-05-30 18:27:09
   * @LastEditors: swc
   * @LastEditTime: Do not edit
   */
  private handleActions(pubApi: string, from: string) {
    const params = this.GT_command.getSelectedData();
    params.title = pubApi;
    params.from = from;
    this.GT_command.doEvent(pubApi, params);
  }

  // 条码扫描
  private bancodeScanClick() {
    this.setExtraSpacePosition('bancodeScan');
    // 打开 条码扫描
    this.extraSpaceRole.bancodeScan = !this.extraSpaceRole.bancodeScan;
    const position = Tsrv.utils.clone(
      Tsrv.getx(this._config, 'bancodeScan.position', 'top'),
      true
    );
    let initSpace =
      Tsrv.utils.clone(
        Tsrv.getx(this._config, 'bancodeScan.initSpace', 5),
        true
      ) / 100;
    if (initSpace < 0.05) {
      initSpace = 0.05;
    }
    if (this.extraSpaceRole.bancodeScan) {
      // this.gridHead.qbeQuery = false;
      Object.keys(this.extraSpaceRole).forEach(key => {
        if (key !== 'bancodeScan') {
          this.extraSpaceRole[key] = false;
        }
      });
      this.extraCollaStyle['--splitTrigger'] = undefined;
      position === 'top'
        ? (this.extraSpace.split = initSpace)
        : position === 'bottom'
        ? (this.extraSpace.split = 1 - initSpace)
        : position === 'left'
        ? (this.extraSpace.split = initSpace)
        : (this.extraSpace.split = 1 - initSpace);
    } else {
      this.extraCollaStyle['--splitTrigger'] = 'none';
      position === 'top'
        ? (this.extraSpace.split = 0)
        : position === 'bottom'
        ? (this.extraSpace.split = 1)
        : position === 'left'
        ? (this.extraSpace.split = 0)
        : (this.extraSpace.split = 1);
    }
  }

  // 初始化 额外的区域 排布方式
  public setExtraSpacePosition(type: string) {
    // enable position
    this.extraCollaStyle['--splitTrigger'] = 'none';
    // const position = this._config?.qbeSearch?.position ?? '';
    const position = Tsrv.utils.clone(
      Tsrv.getx(this._config, `${type}.position`, ''),
      true
    );
    if (!Tsrv.utils.noValue(position)) {
      if (position === 'top') {
        this.extraSpace.split = 0;
        this.extraSpace.mode = 'vertical';
        this.extraSpace.extraPosition = 'top';
        this.extraSpace.mainPosition = 'bottom';
      } else if (position === 'bottom') {
        this.extraSpace.split = 1;
        this.extraSpace.mode = 'vertical';
        this.extraSpace.extraPosition = 'bottom';
        this.extraSpace.mainPosition = 'top';
      } else if (position === 'left') {
        this.extraSpace.split = 0;
        this.extraSpace.mode = 'horizontal';
        this.extraSpace.extraPosition = 'left';
        this.extraSpace.mainPosition = 'right';
      } else if (position === 'right') {
        this.extraSpace.split = 1;
        this.extraSpace.mode = 'horizontal';
        this.extraSpace.extraPosition = 'right';
        this.extraSpace.mainPosition = 'left';
      }
    }
  }
}
</script>
<style scoped lang="scss">
.wy-panel {
  height: 100%;
  overflow: hidden;
  position: relative;
  &.is--max {
    width: 100%;
    left: 0;
    top: 0;
    z-index: 1000;
    position: fixed;
  }
  ::v-deep .base-grid-toolbar {
    .grid-toolbar-left {
      left: 0px;
    }
  }
  .panel-content {
    width: 100%;
    height: 100%;
    padding-bottom: 20px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  ::v-deep .ivu-tabs {
    .ivu-tabs-content {
      height: 100%;
    }
  }

  ::v-deep .wy-panel-split > .ivu-split-vertical > .ivu-split-trigger-con {
    // 分割线显示与隐藏
    display: var(--splitTrigger);
  }
}
.panel-toolbar {
  height: 42px;
  width: 100%;
  position: relative;
  border-bottom: 1px solid var(--border-color-emps);
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05);
  background-color: var(--basepanel-toolbar-bg-color);
}
.panel-form {
  height: initial;
  padding: 6px 10px 4px;
  &.panel-form-bottom {
    padding-bottom: 0;
  }
  .panel-form-title {
    font-weight: bold;
    padding: 0 20px;
    height: 30px;
    line-height: 40px;
  }
  ::v-deep .ivu-tabs {
    .ivu-tabs-bar {
      .ivu-tabs-nav-container {
        height: 25px;
        font-size: 11px;
        .ivu-tabs-nav-wrap > .ivu-tabs-nav-scroll > .ivu-tabs-nav {
          margin-left: 10px;
          .ivu-tabs-tab {
            padding: 0 10px;
            background: #f8f8f9;
            line-height: 25px;
            margin-right: 5px;
            border: 1px solid var(--default-border-color);
          }
          .ivu-tabs-tab-active {
            font-weight: normal;
            background: #fff;
            border-bottom: none;
            border-color: #57a3f3 !important;
          }
        }
      }
    }
    .ivu-tabs-content {
      padding: 0px 2px;
    }
  }
}
.panel-table {
  flex: 1;
  overflow: hidden;
  ::v-deep .grid-toolbar-left {
    display: none !important;
  }
  ::v-deep .vxe-toolbar {
    box-shadow: none;
    z-index: 1;
  }
  ::v-deep .ivu-tabs {
    .ivu-tabs-bar {
      margin-bottom: 35px;
      .ivu-tabs-nav-container {
        height: 25px;
        font-size: 11px;
        .ivu-tabs-nav-wrap > .ivu-tabs-nav-scroll > .ivu-tabs-nav {
          .ivu-tabs-tab {
            padding: 0 10px;
            background: #f8f8f9;
            line-height: 25px;
            margin-right: 5px;
            border: 1px solid var(--default-border-color);
          }
          .ivu-tabs-tab-active {
            font-weight: normal;
            background: #fff;
            border-bottom: none;
            border-color: #57a3f3 !important;
          }
        }
      }
    }
    .ivu-tabs-content {
      height: calc(100% - 25px);
      padding: 0px 2px;
      margin-top: -36px;
    }
  }
}
.panel-search {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  box-shadow: 0 -5px 4px rgba(0, 0, 0, 0.2);
  .panel-search-simple-form {
    width: 100%;
    padding: 10px 0;
    > div {
      overflow-y: auto;
      overflow-x: hidden;
      max-height: 200px;
    }
  }
  .panel-search-result {
    width: 100%;
    flex: 1;
  }
  .panel-search-header {
    height: 42px;
    border-bottom: 1px solid var(--border-color-emps);
    width: 100%;
    .panel-search-left {
      margin-left: 10px;
      button {
        float: left;
      }
      span {
        float: left;
        line-height: 42px;
        padding: 0 10px;
        font-weight: bold;
      }
    }
    ::v-deep .ivu-btn {
      padding: 0 7px;
      margin: 6px 0;
      height: 30px;
      line-height: 30px;
      border-radius: 15px;
      overflow: hidden;
      .ivu-icon {
        height: 30px;
        line-height: 30px;
        border-radius: 15px;
        overflow: hidden;
      }
      span {
        display: flex;
      }
      .toolText {
        margin-left: 7px;
        margin-right: 3px;
        line-height: 30px;
        transition: var(--animation-hover);
        font-weight: normal;
      }
      &.primary {
        background-color: var(--default-hover-font-color);
        .ivu-icon {
          color: #fff;
        }
        span {
          color: #fff;
        }
      }
    }
    .panel-search-right {
      float: right;
      margin-right: 10px;
      button {
        float: right;
        margin-left: 5px;
      }
    }
  }
}
.custom-search {
  height: 100%;
  padding: 6px;
  .search-conditions {
    // height: calc(100% - 10px);
    overflow-y: auto;
    overflow-x: hidden;
    display: flex;
    flex-direction: column;
    gap: 6px;
    .condition-form {
      display: flex;
      flex-direction: column;
      border: 1px dashed #ccc;
      .condition-forms {
        margin-left: 6px;
      }

      > span {
        font-weight: bold;
        padding: 8px 22px;
      }
      .cover {
        padding: 6px;
        display: flex;
        flex-direction: row;
      }
    }
    .condition-select {
      width: 36px;
      height: 100%;
      margin-right: 8px;
      margin-top: 4px;
      label {
        margin: 8.5px 12px;
      }
    }
  }
  .search-actions {
    height: 50px;
    width: 100%;
    padding: 12px 0;
    ::v-deep .ivu-btn {
      float: right;
      margin-right: 15px;
    }
  }
}
.custom-search-reset {
  margin-left: 15px;
}

.tags {
  position: absolute;
  top: 45px;
  right: 0;
  height: 100px;
  width: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 20;
  i {
    font-size: 65px;
    // color: indianred;
  }
  .audit-checked {
    display: none;
  }
}

.main-container {
  width: 100%;
  height: 100%;
  // overflow: hidden;

  // ::v-deep .vxe-toolbar {
  //   .vxe-custom--option-wrapper {
  //     .vxe-custom--body {
  //       max-height: var(--vxe-toolbar--custom-body-maxheight);
  //     }
  //   }
  // }
}
.extra-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  .extra-content {
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: hidden;
  }
}
</style>
